Encuesta Intercensal 2015

La Encuesta Intercensal se guarda en un un archivo .RData.

data <- read_sav("~/Persona.-Encuesta Intercensal 2015.sav")

save(data, 
      file = paste0(here::here(), "/Bases/Encuesta Intercensal_2015.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

Posibles variables que se pueden contemplar en la migración laboral

  • EDAD

  • SEXO

  • AFRODES

  • HLENGUA

  • QDIALECT_INALI

  • PERTE_INDIGENA

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • ALFABET

  • SITUA_CONYUGAL

  • HIJOS_NAC_VIVOS

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • CONACT Situación laboral

  • OCUPACION_C Cuál fue la ocupación de (NOMBRE) la semana pasada? Por ejemplo: técnico electricista, maestra de primaria, vendedora de frutas, albañil, mecánico de autos

  • SITTRA Situación de trabajo

  • VACACIONES

  • SERVICIO_MEDICO

  • INCAP_SUELDO

  • INGTRMEN

  • ACTIVIDADES_C ¿A qué se dedica el negocio, empresa o lugar donde trabajó (NOMBRE)? Por ejemplo: hacer muebles de madera, hacer escobas, reparar autos, vender ropa usada, armar televisores..

  • TIE_TRASLADO_TRAB

  • MED_TRASLADO_TRAB1

  • MED_TRASLADO_TRAB2

  • MED_TRASLADO_TRAB3

load(paste0(here::here(), "/Bases/Encuesta Intercensal_2015.RData"))

mydata <- data %>%
           select(CVE_ENT, NOM_ENT, MUN, NOM_MUN, ENT_MUN, ENT_PAIS_TRAB, MUN_TRAB, ENT_MUN_TRAB, 
                  EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, PERTE_INDIGENA, NIVACAD, ALFABET, 
                  SITUA_CONYUGAL, HIJOS_NAC_VIVOS, CONACT, OCUPACION_C, SITUACION_TRAB, VACACIONES, 
                  SERVICIO_MEDICO, INCAP_SUELDO, INGTRMEN, ACTIVIDADES_C, TIE_TRASLADO_TRAB,  
                  MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3, FACTOR, ESTRATO, UPM) %>%
            rename("CVE_MUN" = "ENT_MUN",
                   "CVE_MUN_TRABAJO" = "ENT_MUN_TRAB")

save(mydata, file = paste0(here::here(), "/Bases/03_Movilidad laboral_2015.RData"))

✔️A partir de aquí se pueden correr los códidos 👇.
Se carga el archivo Migracion laboral_2015.RData.

load(file = paste0(here::here(), "/Bases/03_Movilidad laboral_2015.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>% 
           select(CVE_ENT, NOM_ENT, MUN, NOM_MUN, CVE_MUN, ENT_PAIS_TRAB, MUN_TRAB, CVE_MUN_TRABAJO,
                  CONACT, EDAD, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1)  %>%
             ungroup()

Entidades

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento. 
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos. 
Se genera un vector con las claves de los municipios.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)

nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")

est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2015.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()

# Se le asignan las etiquetas a los nombres de los estados 
levels(mydata$NOM_ENT) <- estados

Población ocupada de 12 años y más

Se identifica a la población ocupada de 12 años y más.

filter((EDAD >= 12 & EDAD != 999) & (CONACT >= 10 & CONACT <= 20))'.

Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   filter(CVE_MUN_TRABAJO %in% municipios)  # Filtro del lugar de trabajo dentro del país. 

Población ocupada de 12 años y más

Población economicámente activa de 12 años y más

Nivel estatal

Migración laboral

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población ocupada de 12 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       as.data.frame() %>%
        mutate(EDAD = as.numeric(.$EDAD)) %>%
         subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
          filter(ENT_PAIS_TRAB %in% estados) %>%
           svydesign(data = ., id = ~UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/MC_estado.RDS"))

Se genera una matriz cruzada de migración laboral a nivel estatal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/MC_estado.RDS"))

Migrantes <- svytable(~ENT_PAIS_TRAB + CVE_ENT, design = MC)

La función cross_cases() de la paquetería expss se utiliza para crear tablas de contingencia cruzadas a partir de dos o más variables categóricas. Utilizando el comando weight, permite ponderar las observaciones “factores de expansión” en la tabla.

Se quita la diagonal a la matriz cruadrada con la función diag.remove() de la paquetería sna, donde esta función reemplaza los elementos de la diagonal principal de una matriz por un valor nulo o por el valor especifico.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ENT, ENT_PAIS_TRAB, weight = Freq) %>%
                as.data.frame() %>%
                 slice(-33) %>% 
                  select(-row_labels) 

rownames(Migrantes)<- nom_estados
colnames(Migrantes) <- nom_estados

save(Migrantes, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

wb <- createWorkbook()
addWorksheet(wb, "MTrabajo 2015")
writeData(wb, 1, Migrantes, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel estatal, 2015

Matriz de migración laboral, 2015
Nivel estatal
Entidad Aguascalientes Baja California Baja California Sur Campeche Coahuila de Zaragoza Colima Chiapas Chihuahua Ciudad de México Durango Guanajuato Guerrero Hidalgo Jalisco México Michoacán de Ocampo Morelos Nayarit Nuevo León Oaxaca Puebla Querétaro Quintana Roo San Luis Potosí Sinaloa Sonora Tabasco Tamaulipas Tlaxcala Veracruz de Ignacio de la Llave Yucatán Zacatecas
Aguascalientes 506233 84 51 12 79 51 11 125 756 107 1030 12 14 3126 345 36 38 43 176 0 28 245 23 237 92 67 8 137 10 41 48 2544
Baja California 0 1338240 486 21 83 49 21 117 724 14 112 91 41 314 276 83 0 95 77 35 0 43 0 66 223 1685 0 12 0 64 2 26
Baja California Sur 13 139 313523 6 38 3 0 6 147 0 25 3 48 142 89 0 0 9 74 0 30 10 4 0 316 16 0 0 0 2 0 0
Campeche 0 0 0 348016 1 0 48 7 201 3 0 13 9 16 62 0 4 4 14 22 7 6 707 0 27 3 495 70 0 217 2256 0
Coahuila de Zaragoza 95 108 27 18 1092132 6 4 1041 982 17570 98 37 69 281 330 46 126 24 5104 7 84 113 33 198 103 360 11 549 0 93 3 1139
Colima 28 24 5 20 52 299876 14 39 227 3 105 40 5 2470 78 1360 0 40 31 4 0 27 13 26 61 107 0 29 0 36 0 28
Chiapas 0 180 14 612 49 66 1591663 26 948 10 47 49 8 266 407 72 16 25 190 940 192 28 911 7 54 609 5053 81 6 674 153 12
Chihuahua 69 130 36 16 669 3 23 1339357 583 631 109 12 0 225 143 48 0 5 333 18 2 138 0 19 242 741 30 34 0 34 10 211
Ciudad de México 219 439 70 672 205 59 531 190 3775053 62 1160 1445 3395 1034 170901 861 3525 110 987 450 3428 1980 296 385 143 330 207 338 498 1327 244 71
Durango 45 26 14 61 23054 39 2 982 243 546514 42 103 2 327 232 17 3 84 729 37 4 30 4 50 479 194 13 87 0 106 11 1130
Guanajuato 310 233 33 222 224 73 9 125 1974 145 2087948 199 157 2398 1964 5069 63 252 468 36 223 28644 37 3534 141 1195 91 158 24 149 14 253
Guerrero 28 160 280 81 67 104 73 33 1884 0 108 1099068 32 205 1911 1539 2024 98 46 425 335 92 237 46 2967 642 46 20 6 140 15 30
Hidalgo 81 83 47 305 266 107 162 162 24103 132 772 260 930210 659 26247 217 271 34 934 167 2233 4356 120 845 456 348 136 595 990 2107 63 201
Jalisco 3923 270 154 153 186 3546 22 65 2479 96 4999 164 109 3067858 1222 3731 85 7568 632 106 246 618 284 257 438 286 34 134 20 236 72 690
México 376 629 259 697 471 252 491 496 1320748 331 3122 2807 26900 2668 4731052 2629 5543 201 2576 922 4385 11272 533 974 415 559 528 1132 1189 2640 183 459
Michoacán de Ocampo 63 73 24 54 81 427 57 40 4702 45 7680 2215 178 4774 5939 1575965 56 145 242 99 143 2593 37 157 166 176 87 60 9 176 16 97
Morelos 2 11 9 79 38 3 67 34 11452 9 82 2020 216 159 5474 124 736600 9 91 161 1928 170 35 22 100 36 39 27 32 203 14 17
Nayarit 3 192 64 82 13 147 4 57 283 26 113 12 5 12468 89 33 8 430672 80 112 18 43 64 71 468 156 16 16 0 61 3 16
Nuevo León 69 126 0 226 2809 34 19 302 2114 105 249 3 74 420 674 87 110 57 2040520 57 178 221 43 500 117 209 86 3058 13 303 37 444
Oaxaca 12 181 42 791 86 24 420 58 1972 7 51 450 43 164 1187 77 106 21 207 1204955 915 62 39 31 265 633 202 60 13 4194 22 7
Puebla 97 695 212 539 192 45 459 174 12952 36 513 1007 2113 743 9753 226 2003 64 704 3215 2107487 644 190 225 147 1336 648 330 8644 9370 164 45
Querétaro 145 60 0 70 106 7 152 51 3918 18 5474 153 603 631 2695 465 68 20 403 62 203 806766 63 418 76 52 38 106 3 114 2 131
Quintana Roo 0 0 0 334 16 0 130 0 504 0 0 14 0 203 163 2 7 10 40 10 73 86 662309 10 0 6 145 36 13 100 879 0
San Luis Potosí 432 71 39 132 383 52 5 201 864 84 1114 62 389 642 651 118 0 10 3101 32 129 1054 9 921569 452 65 43 2145 0 1860 8 1018
Sinaloa 9 512 315 777 132 148 121 587 602 658 36 128 0 561 237 68 0 525 252 55 66 49 15 8 1100924 2079 50 53 0 34 23 97
Sonora 1 2943 84 24 24 20 10 618 534 113 16 22 0 192 154 40 0 21 239 16 7 14 5 75 1098 1103044 92 7 3 47 109 109
Tabasco 9 19 0 9221 112 3 6995 19 320 45 39 18 14 93 109 22 0 14 331 197 86 6 475 33 31 11 779580 102 9 2174 250 39
Tamaulipas 22 34 7 2963 272 58 106 4 834 0 151 7 139 165 324 78 4 66 2919 136 54 167 15 1311 3 56 455 1243000 26 6273 69 47
Tlaxcala 58 58 104 112 73 33 129 112 6402 11 227 249 1694 298 5348 183 480 29 392 255 48203 297 112 100 73 298 119 199 401290 954 27 76
Veracruz de Ignacio de la Llave 64 462 374 9895 405 115 810 246 10029 73 353 407 2790 849 7073 315 195 31 2128 4168 8522 486 376 797 666 1320 4530 17338 288 2727361 264 46
Yucatán 0 59 8 4338 5 1 139 20 912 0 0 11 0 136 322 44 7 2 131 11 14 92 13353 0 17 50 491 39 0 119 822799 28
Zacatecas 5821 26 4 2 435 98 13 220 250 583 311 38 17 1117 152 21 12 135 477 12 27 96 10 2419 211 116 8 79 0 59 0 459707
Fuente: Estimaciones del CONAPO.

Gráfico dinámico

Gráfico dinámico de migración laboral a nivel estatal.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

names <- c("Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila", "Colima", 
           "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",    
           "México", "Michoacán", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
           "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
           "Veracruz", "Yucatán", "Zacatecas")

# Paleta de colores
paleta <- colorRampPalette(pals::ocean.matter(100))(50)

p <- chorddiag(tabla, 
               groupNames = names,
               groupColors = paleta, 
               groupnamePadding = 10, 
               #height = 700, 
               #width = 700,
               margin = 120,
               groupThickness = 0.07,
               groupPadding = 3,
               groupnameFontsize = 12,
               fadeLevel = '0.1',
               tickInterval = seq(0, 500000, 10000),
               chordedgeColor = "transparent",
               showZeroTooltips = FALSE,
               showTicks = TRUE)

# Ajusta las etiquetas usando JavaScript para modificar su posición
p <- htmlwidgets::onRender(p, '
      function(el, x) {
        d3.selectAll(".group text")
          .attr("text-anchor", "middle")
          .attr("dx", "0")  
          .attr("dy", "0.75em"); 
      }
')

# Crear un contenedor div y aplicar estilos CSS para centrarlo
#p <- tags$div(style = "display: flex; justify-content: center; align-items: center;", p)

p
p %>% 
 mapshot(url = paste0(here::here(),"/images/MTrab_2015.html"))

#htmlwidgets::saveWidget(p, paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2015/MTrab a nivel estatal 2015.html"), selfcontained = TRUE)
#require(webshot)
#webshot(url = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2015/MTrab a nivel estatal 2015.html"),
 #         file = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2015/MTrab a nivel estatal 2015.png"),
  #                cliprect = "viewport")

Gráficos migración laboral

ChordDiagram

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0)  

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Paleta de colores
#paleta <- colorRampPalette(pals::ocean.matter(100))(50)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2015/ChordDiagram de MTrab a nivel estatal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0.4,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) 

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#filtro_mig <- sapply(1:32, function(x)
 #                     mean(tail(sort(tabla1[[x]]), 1), na.rm = TRUE))
#p <- data.frame(estados = est,
 #               filtro_estados = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Filtro a nivel estatal.xlsx"))

filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Filtro a nivel estatal.xlsx"), colNames = TRUE) %>% 
               pull(filtro_estados)

tabla1 <- migration_flows_states(tabla = tabla, 
                                 filtro_mig = filtro_mig, 
                                 filtro_est = filtro_est, 
                                 category = estado, 
                                 group = "Otro estados")

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                 name = "Total",,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Matriz MTrab por estados_2015_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Tabla MTrab por estados.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Tabla MTrab por estados.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_ENT", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_ENT", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(),  "/Output/Estado/03_Movilidad laboral/2015/Matriz MTrab por estados_2015_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Tabla MTrab por estados.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2015/ChordDiagram de MTrab para cada estado.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Estado/03_Movilidad laboral/2015/Etiquetas a nivel estatal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(nom_estados))

Gráfico Sankey

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

Migrantes <- Migrantes %>%
              sna::diag.remove(remove.val = 0)  

rownames(Migrantes) <- stringr::str_wrap(nom_estados, 50)
colnames(Migrantes) <- stringr::str_wrap(nom_estados, 50)

# Matiz migración laboral (Población de 12 años y más)
tabla <- Migrantes %>% 
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             as_tibble() %>%
              mutate(rn = forcats::fct_relevel(.$rn, nom_estados),
                     cn = forcats::fct_relevel(.$cn, nom_estados)) %>%
               filter(value >= 0)  
p <- tabla %>% 
       ggplot(aes(axis1 = rn, 
                   axis2 = cn, 
                    y = value),  # c("value", "freq", "tasa")
               reverse = FALSE, 
                na.rm = TRUE) +
        geom_alluvium(aes(fill = rn),
                       curve_type = "quintic", 
                        color = "transparent", 
                         alpha = 0.85, 
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
          geom_stratum(aes(fill = cn), 
                        color = "white", 
                         alpha = 0.65,  
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.2,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .2, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() + 
              theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(1, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.35)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2015/GSankey de MTrab a nivel estatal.pdf")
ggexport(p, width = 14, height = 10, dpi = 400, filename = path)

Desagregado por estado

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% estados | .$cn %in% estados), value, 0)) %>%
                mutate(rn = forcats::fct_relevel(.$rn, estados),
                       cn = forcats::fct_relevel(.$cn, estados)) 
p <- lapply(1:32, function(x){
                   tabla <- tabla %>%
                             mutate(rn = forcats::fct_relevel(.$rn, estados),
                                    cn = forcats::fct_relevel(.$cn, estados)) %>%
                              mutate(value = ifelse(.$rn %in% estados[x] | .$cn %in% estados[x], value, 0)) 
 
                    tabla %>% 
                     ggplot(aes(axis1 = rn, 
                                 axis2 = cn, 
                                  y = value),  # c("value", "freq", "tasa")
                             reverse = FALSE, 
                              na.rm = TRUE) + 
                      geom_alluvium(aes(fill = rn),  
                                     color = "transparent", 
                                      alpha = 0.8, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                       geom_stratum(aes(fill = rn), 
                                     color = "#F1F1F1", 
                                      alpha = 1, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                         geom_text_repel(aes(label = ifelse(after_stat(x)  == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                             fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = -.2, 
                                               force = 1,
                                                        force_pull = 0,
                                                         family = "montserrat",
                                                          reverse = FALSE) +
                          geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                              fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = .2, 
                                               force = 1,
                                                force_pull = 0,
                                                 family = "montserrat",
                                                  reverse = FALSE) +
                            theme_void() + 
                             theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                    text = element_text(family = "montserrat"),
                                     axis.text = element_blank(),
                                      axis.title = element_blank(),
                                       strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                        legend.key.size = unit(0.5, "cm"),
                                         legend.text = element_text(size = 9, family = "montserrat"),
                                          legend.position = c(1, .5)) + 
                              scale_x_discrete(expand = c(-0.1, 0.35)) +
                               scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                                guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                                 labs(fill = "", 
                                      color = "")
              }
  )

path = paste0(here::here(),"/Graficos/Estado/03_Movilidad laboral/2015/GSankey de MTrab desagregado por estados_Absolutos.pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ENT) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población ocupada de 12 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_ENT) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2015/Matriz de MTrab a nivel estatal 2015.RData"))

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                tidyr::gather(CVE_ENT, Value, -rowname)%>%
                 filter(rowname == CVE_ENT) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos laborales
Inmigrantes <- Migrantes %>% 
                sna::diag.remove(remove.val = 0) %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "CVE_ENT") %>%
                   melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                    mutate_at(vars(3), as.numeric) %>%
                     as_tibble() %>%
                      filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                       group_by(CVE_ENT) %>%
                        summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               sna::diag.remove(remove.val = 0) %>%
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_ENT") %>%
                  melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                      group_by(ENT_PAIS_TRAB) %>%
                       summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                        rename("CVE_ENT" = "ENT_PAIS_TRAB")

tabla <- Pob.Total %>%
          left_join(., Pob.ocupada, by = c("CVE_ENT")) %>%
          left_join(., Residentes, by = c("CVE_ENT")) %>%
          left_join(., Inmigrantes, by = c("CVE_ENT")) %>%
          left_join(., Emigrantes, by = c("CVE_ENT")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Indicadores de MTrab a nivel estatal 2015.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2015/Indicadores de MTrab a nivel estatal 2015.RData"))
Indicadores de movilidad laboral
Nivel estatal
Clave de Entidad Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001 1 312 544 540 692 506 233 9 576 11 994 −2 418 21 570 2.1 2.6 −0.5 −23 988
002 3 315 766 1 463 802 1 338 240 4 760 8 027 −3 267 12 787 0.4 0.7 −0.3 −16 054
003 712 029 326 564 313 523 1 120 2 762 −1 642 3 882 0.4 1.1 −0.6 −5 524
004 899 931 363 555 348 016 4 192 32 535 −28 343 36 727 1.3 10.3 −9.0 −65 070
005 2 954 915 1 182 013 1 092 132 28 659 30 626 −1 967 59 285 2.8 3.0 −0.2 −61 252
006 711 235 319 574 299 876 4 872 5 573 −701 10 445 1.9 2.2 −0.3 −11 146
007 5 217 908 1 698 428 1 591 663 11 705 11 047 658 22 752 0.7 0.6 0.0 −22 094
008 3 556 574 1 427 766 1 339 357 4 514 6 157 −1 643 10 671 0.4 0.5 −0.1 −12 314
009 8 918 653 4 205 072 3 775 053 195 562 1 414 643 −1 219 081 1 610 205 6.0 43.1 −37.2 −2 829 286
010 1 754 754 615 419 546 514 28 150 20 917 7 233 49 067 4.8 3.5 1.2 −41 834
011 5 853 677 2 257 943 2 087 948 48 417 28 138 20 279 76 555 2.4 1.4 1.0 −56 276
012 3 533 251 1 182 214 1 099 068 13 674 12 051 1 623 25 725 1.2 1.0 0.1 −24 102
013 2 858 359 1 048 451 930 210 67 459 39 064 28 395 106 523 6.9 4.0 2.9 −78 128
014 7 844 830 3 256 882 3 067 858 32 825 37 746 −4 921 70 571 1.2 1.4 −0.2 −75 492
015 16 187 608 6 507 365 4 731 052 1 396 387 244 551 1 151 836 1 640 938 24.6 4.3 20.3 −489 102
016 4 584 471 1 699 569 1 575 965 30 611 17 611 13 000 48 222 1.9 1.1 0.8 −35 222
017 1 903 811 802 856 736 600 22 663 14 754 7 909 37 417 3.3 2.2 1.2 −29 508
018 1 181 050 467 031 430 672 14 723 9 751 4 972 24 474 3.6 2.4 1.2 −19 502
019 5 119 504 2 150 819 2 040 520 12 744 24 108 −11 364 36 852 0.7 1.3 −0.6 −48 216
020 3 967 889 1 283 262 1 204 955 12 342 11 767 575 24 109 0.9 0.9 0.0 −23 534
021 6 168 883 2 267 222 2 107 487 57 485 71 763 −14 278 129 248 2.7 3.4 −0.7 −143 526
022 2 038 372 863 776 806 766 16 307 53 682 −37 375 69 989 2.2 7.4 −5.2 −107 364
023 1 501 562 690 682 662 309 2 781 18 043 −15 262 20 824 0.5 3.3 −2.8 −36 086
024 2 717 820 987 058 921 569 15 165 12 821 2 344 27 986 1.6 1.4 0.3 −25 642
025 2 966 321 1 162 695 1 100 924 8 197 10 047 −1 850 18 244 0.8 1.0 −0.2 −20 094
026 2 850 330 1 178 848 1 103 044 6 637 13 741 −7 104 20 378 0.7 1.4 −0.7 −27 482
027 2 395 272 861 144 779 580 20 796 13 701 7 095 34 497 2.6 1.7 0.9 −27 402
028 3 441 698 1 355 011 1 243 000 16 765 27 031 −10 266 43 796 1.4 2.3 −0.9 −54 062
029 1 272 847 495 846 401 290 66 705 11 796 54 909 78 501 15.1 2.7 12.4 −23 592
030 8 112 505 2 956 089 2 727 361 75 415 33 907 41 508 109 322 2.7 1.2 1.5 −67 814
031 2 097 175 868 376 822 799 20 349 4 961 15 388 25 310 2.7 0.7 2.1 −9 922
032 1 579 209 506 456 459 707 12 769 9 011 3 758 21 780 2.4 1.7 0.7 −18 022
Fuente: Estimaciones del CONAPO.

Nivel municipal

Movilidad laboral

Matrices

#Clave de los municipios 2015 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                    nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de trabajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(EDAD = as.numeric(.$EDAD)) %>%
                   subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20) 
                          ) %>%
                    select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT) %>%
                     filter(CVE_MUN_TRABAJO %in% municipios) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel municipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel municipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Laboral")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel municipal 2015.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2015 - 2015

Matriz de movilidad laboral
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 349088 325 586 0 3322 613 558 31 87 369 3201 0 0 0 70 0 0 0 0 51 0 0 0 12 0 0 0 0 0
001002 2809 8687 10 4 64 172 46 3 72 50 322 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 223 0 18721 0 57 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 615 0 1 2679 115 27 247 4 25 0 538 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 16934 42 282 29 28940 138 147 63 37 27 1963 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 2288 111 15 17 673 9232 531 43 237 8 2696 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 2131 63 30 236 410 337 11655 34 210 8 1417 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 407 3 3 3 41 73 32 2071 2 4 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 794 55 12 8 102 244 490 13 3714 2 671 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 1867 66 14 2 20 4 4 0 2 3561 40 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 4375 54 18 3 870 400 98 26 30 10 10829 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 200010 146 145 412 95 0 72 0 53 0 0 2 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 107 392362 115 329 0 0 25 0 29 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 52 87 37725 990 41 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 564 274 1487 664036 2991 0 0 27 42 0 0 19 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 145 19 25 4620 31195 0 0 24 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 12 0 0 6 0 28386 25 121 31 64 0 6 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 58 0 0 0 0 0 23932 16 5 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 15 0 0 33 0 154 169 119392 753 15 0 0 0 0 0 0 0 0
003008 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 472 132246 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 21 21 14 4 7614 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15525 1160 343 210 182 118 5 57
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56 117769 1071 765 227 169 68 122
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 164 99583 30 0 0 16 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 1153 655 33436 2 11 18 12
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 180 1181 311 104 8214 37 17 270
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 43 401 59 43 6 12405 3 39
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 62 0 0 0 2943 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 669 31 15 40 14 1 3196
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 113 278 52 0 1 3 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel municipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE))

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#### Se anexa el filtro de estados filter(value > 100000000 & rn != estado[x]) %>% 
#### De esta manera solo se contemplan a los municipios
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                         tabla1[[i]] %>%
#                          as.data.frame() %>%
#                           adorn_totals(c("row", "col"), 
#                                         fill = "-", 
#                                          na.rm = TRUE, 
#                                           ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                            select(`Otros estados`) %>%
#                             slice(nrow(.)) %>%
#                              mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                               pull(`Otros estados`)
# })

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                   tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      adorn_totals(c("row", "col"), 
#                                                    fill = "-", 
#                                                     na.rm = TRUE, 
#                                                      ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                       slice(nrow(.)) %>%
#                                        mutate(Total = .$Total/50) %>%
#                                        pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb,  
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel municipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2015/ChordDiagram de MTrab desagregado por municipio.pdf"

## Gráficos a nivel municipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2015/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 10, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
############# Población ocupada de 12 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)
                         ) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel municipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de movilidad laboral a nivel municipal 2015.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de movilidad laboral a nivel municipal 2015.RData"))
Indicadores de movilidad laboral
Nivel municipal
CVE_MUN Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 877 190 382 550 349 088 14 667 42 159 −27 492 56 826 4.66 13.39 −8.7 −84 318
001002 46 464 13 914 8 687 4 146 1 290 2 856 5 436 27.47 8.55 18.9 −2 580
001003 56 048 20 099 18 721 405 1 232 −827 1 637 2.13 6.47 −4.3 −2 464
001004 15 577 4 869 2 679 1 873 445 1 428 2 318 36.64 8.71 27.9 −890
001005 120 405 51 020 28 940 20 201 5 798 14 403 25 999 47.14 13.53 33.6 −11 596
001006 46 473 16 904 9 232 6 811 2 037 4 774 8 848 42.99 12.86 30.1 −4 074
001007 53 866 17 891 11 655 5 235 2 380 2 855 7 615 29.18 13.27 15.9 −4 760
001008 8 896 2 994 2 071 695 219 476 914 23.38 7.37 16.0 −438
001009 20 926 6 446 3 714 2 463 731 1 732 3 194 35.99 10.68 25.3 −1 462
001010 20 245 6 276 3 561 2 164 519 1 645 2 683 32.64 7.83 24.8 −1 038
001011 46 454 17 729 10 829 6 041 11 207 −5 166 17 248 37.65 69.84 −32.2 −22 414
002001 486 639 210 634 200 010 1 067 1 474 −407 2 541 0.61 0.85 −0.2 −2 948
002002 988 417 429 396 392 362 2 215 4 062 −1 847 6 277 0.62 1.15 −0.5 −8 124
002003 102 406 42 851 37 725 1 207 1 832 −625 3 039 3.32 5.04 −1.7 −3 664
002004 1 641 570 741 226 664 036 6 388 8 581 −2 193 14 969 1.07 1.44 −0.4 −17 162
002005 96 734 39 695 31 195 4 954 3 133 1 821 8 087 14.52 9.19 5.3 −6 266
003001 72 564 29 698 28 386 290 180 110 470 1.13 0.70 0.4 −360
003002 60 171 25 292 23 932 96 491 −395 587 0.45 2.30 −1.8 −982
003003 272 711 125 680 119 392 1 473 1 409 64 2 882 1.48 1.41 0.1 −2 818
003008 287 671 137 887 132 246 804 2 024 −1 220 2 828 0.76 1.90 −1.1 −4 048
Fuente: Estimaciones del CONAPO.

Movilidad Intramunicipal

Matrices

#Clave de los municipios 2015 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de tranajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 1) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_intramunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2015

Matriz de movilidad laboral
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 349088 325 586 0 3322 613 558 31 87 369 3201 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 2809 8687 10 4 64 172 46 3 72 50 322 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 223 0 18721 0 57 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 615 0 1 2679 115 27 247 4 25 0 538 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 16934 42 282 29 28940 138 147 63 37 27 1963 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 2288 111 15 17 673 9232 531 43 237 8 2696 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 2131 63 30 236 410 337 11655 34 210 8 1417 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 407 3 3 3 41 73 32 2071 2 4 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 794 55 12 8 102 244 490 13 3714 2 671 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 1867 66 14 2 20 4 4 0 2 3561 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 4375 54 18 3 870 400 98 26 30 10 10829 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 200010 146 145 412 95 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 107 392362 115 329 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 52 87 37725 990 41 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 564 274 1487 664036 2991 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 145 19 25 4620 31195 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28386 25 121 31 64 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23932 16 5 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 154 169 119392 753 15 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 472 132246 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 21 14 4 7614 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15525 1160 343 210 182 118 5 57
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56 117769 1071 765 227 169 68 122
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 164 99583 30 0 0 16 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 1153 655 33436 2 11 18 12
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 180 1181 311 104 8214 37 17 270
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 43 401 59 43 6 12405 3 39
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 62 0 0 0 2943 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 669 31 15 40 14 1 3196
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 113 278 52 0 1 3 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)  

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig)
#write.table(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)

################################################################################
## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                  tabla1[[i]] %>%
#                                   as.data.frame() %>%
#                                    adorn_totals(c("row", "col"), 
#                                                  fill = "-", 
#                                                   na.rm = TRUE, 
#                                                    ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(Total) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(Total = .$Total/100) %>%
 #}
#)

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
 
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intramunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2015/ChordDiagram de Mtrab desagregado a nivel intramunicipal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2015/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 0) %>% 
               pull(rn)
################################################################################

tabla1 <- lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ substr(.$rn, 1, 3)),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ substr(.$cn, 1, 3))) %>%

                     mutate(value = ifelse(.$rn != .$cn, .$value, 0)) %>%
                      filter(value > 0) 
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)
p[[3]]
path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2015/GSankey de MR5a desagregado a nivel intramunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 12 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intramunicipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de MTrab a nivel intramunicipal 2015.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de MTrab a nivel intramunicipal 2015.RData"))
Indicadores de movilidad laboral
Nivel intramunicipal
CVE_MUN Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 877 190 382 550 349 088 9 092 32 443 −23 351 41 535 2.887 10.30 −7.4 −64 886
001002 46 464 13 914 8 687 3 552 719 2 833 4 271 23.532 4.76 18.8 −1 438
001003 56 048 20 099 18 721 283 971 −688 1 254 1.487 5.10 −3.6 −1 942
001004 15 577 4 869 2 679 1 572 302 1 270 1 874 30.754 5.91 24.8 −604
001005 120 405 51 020 28 940 19 662 5 674 13 988 25 336 45.879 13.24 32.6 −11 348
001006 46 473 16 904 9 232 6 619 2 008 4 611 8 627 41.775 12.67 29.1 −4 016
001007 53 866 17 891 11 655 4 876 2 153 2 723 7 029 27.181 12.00 15.2 −4 306
001008 8 896 2 994 2 071 680 217 463 897 22.876 7.30 15.6 −434
001009 20 926 6 446 3 714 2 391 702 1 689 3 093 34.941 10.26 24.7 −1 404
001010 20 245 6 276 3 561 2 019 478 1 541 2 497 30.451 7.21 23.2 −956
001011 46 454 17 729 10 829 5 884 10 963 −5 079 16 847 36.670 68.32 −31.7 −21 926
002001 486 639 210 634 200 010 798 868 −70 1 666 0.458 0.50 0.0 −1 736
002002 988 417 429 396 392 362 551 526 25 1 077 0.155 0.15 0.0 −1 052
002003 102 406 42 851 37 725 1 170 1 772 −602 2 942 3.222 4.88 −1.7 −3 544
002004 1 641 570 741 226 664 036 5 316 6 351 −1 035 11 667 0.892 1.07 −0.2 −12 702
002005 96 734 39 695 31 195 4 809 3 127 1 682 7 936 14.100 9.17 4.9 −6 254
003001 72 564 29 698 28 386 241 175 66 416 0.943 0.68 0.3 −350
003002 60 171 25 292 23 932 21 241 −220 262 0.098 1.13 −1.0 −482
003003 272 711 125 680 119 392 1 091 623 468 1 714 1.095 0.63 0.5 −1 246
003008 287 671 137 887 132 246 498 793 −295 1 291 0.468 0.75 −0.3 −1 586
Fuente: Estimaciones del CONAPO.

Movilidad Intermunicipal

Matrices

#Clave de los municipios 2015 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de trabajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 2) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_intermunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2015

Matriz de movilidad laboral
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 70 0 0 0 0 51 0 0 0 12 0 0 0 0 0
001002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 72 0 53 0 0 2 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 29 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 42 0 0 19 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 12 0 0 6 0 0 0 0 0 0 0 6 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 58 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 15 0 0 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003008 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)
             
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2015/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                                 tabla1[[i]] %>%
#                                  as.data.frame() %>%
#                                   adorn_totals(c("row", "col"), 
#                                                 fill = "-", 
#                                                  na.rm = TRUE, 
#                                                   ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(`Otros estados`) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                       pull(`Otros estados`)
#})


## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                               tabla1[[i]] %>%
#                                as.data.frame() %>%
#                                 select(-c(`Otros estados`)) %>%
#                                  adorn_totals(c("row", "col"), 
#                                                fill = "-", 
#                                                 na.rm = TRUE, 
#                                                  ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    slice(nrow(.)) %>%
#                                     mutate(Total = .$Total/50) %>%
#                                      pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
 wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz MTrab a nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Tabla MTrab a nivel intermunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2015/ChordDiagram de Mtrab desagregado a nivel intermunicipal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2015/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 5000) %>% 
               pull(rn)
################################################################################

tabla1 <-  lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                     mutate(value = ifelse(.$rn != .$cn & (substr(.$rn, 1, 3) %in% estados[x] | substr(.$cn, 1, 3) %in% estados[x]), .$value, 0)) %>%
                      filter(value > 0)  
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2015/GSankey de MR5a desagregado a nivel intermunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 12 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Matriz de movilidad laboral a nivel intermunicipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de MTrab a nivel intermunicipal 2015.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2015/Indicadores de MTrab a nivel intermunicipal 2015.RData"))
Indicadores de movilidad laboral
Nivel intermunicipal
CVE_MUN Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 877 190 382 550 0 5 575 9 716 −4 141 15 291 1.77 3.085 −1.3 −19 432
001002 46 464 13 914 0 594 571 23 1 165 3.94 3.783 0.2 −1 142
001003 56 048 20 099 0 122 261 −139 383 0.64 1.371 −0.7 −522
001004 15 577 4 869 0 301 143 158 444 5.89 2.798 3.1 −286
001005 120 405 51 020 0 539 124 415 663 1.26 0.289 1.0 −248
001006 46 473 16 904 0 192 29 163 221 1.21 0.183 1.0 −58
001007 53 866 17 891 0 359 227 132 586 2.00 1.265 0.7 −454
001008 8 896 2 994 0 15 2 13 17 0.50 0.067 0.4 −4
001009 20 926 6 446 0 72 29 43 101 1.05 0.424 0.6 −58
001010 20 245 6 276 0 145 41 104 186 2.19 0.618 1.6 −82
001011 46 454 17 729 0 157 244 −87 401 0.98 1.521 −0.5 −488
002001 486 639 210 634 0 269 606 −337 875 0.15 0.348 −0.2 −1 212
002002 988 417 429 396 0 1 664 3 536 −1 872 5 200 0.47 0.998 −0.5 −7 072
002003 102 406 42 851 0 37 60 −23 97 0.10 0.165 −0.1 −120
002004 1 641 570 741 226 0 1 072 2 230 −1 158 3 302 0.18 0.374 −0.2 −4 460
002005 96 734 39 695 0 145 6 139 151 0.43 0.018 0.4 −12
003001 72 564 29 698 0 49 5 44 54 0.19 0.020 0.2 −10
003002 60 171 25 292 0 75 250 −175 325 0.35 1.170 −0.8 −500
003003 272 711 125 680 0 382 786 −404 1 168 0.38 0.789 −0.4 −1 572
003008 287 671 137 887 0 306 1 231 −925 1 537 0.29 1.157 −0.9 −2 462
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
mapview 2.11.0 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.